﻿using LY.Manage.BLL;
using LY.Manage.Model;
using LY.Manage.Model.SearchParam;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LY.Manage.WebApp.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        IBLL.IUserInfoService UserInfoService { get; set; }
        IBLL.Itbl_canshuService CanShuService { get; set; }
   
        public ActionResult Index()
        {
           CheckCookieInfo();

            Bindtitile();
            return View();
        }
        /// <summary>
        /// 绑定头底标题
        /// </summary>
        public void Bindtitile()
        {

            var data = CanShuService.LoadEntities(u => u.id == 1).FirstOrDefault();
            ViewBag.HeadTitle = data.value;

        }

        #region 显示验证码
        public ActionResult ShowValidateCode()
        {
            Common.ValidateCode valiateCode = new Common.ValidateCode();

            //产生验证码
            String code = valiateCode.CreateValidateCode(4);

            Session["validateCode"] = code;
            //将验证码画到画布上
            byte[] buffer = valiateCode.CreateValidateGraphic(code);

            return File(buffer, "image/jpeg");

        }
        #endregion


        #region 完成用户登录
        public ActionResult UserLogin()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            string userName = Request["LoginCode"].Trim();

            string userPwd = Request["LoginPwd"].Trim();

            var userInfo = UserInfoService.LoadEntities(
                u => u.UName == userName
                && u.UPwd == userPwd
                && u.DelFlag == (short)Model.EnumType.DeleteEnumType.Normarl
                ).FirstOrDefault();


            sw.Stop();

            long totalTime = sw.ElapsedMilliseconds;

            if (userInfo != null)
            {
                /*
                Session["userInfo"] = userInfo;
                */
                //采用Memcache来存储数据
                //用GUID来当key

                string sessionId = Guid.NewGuid().ToString();

                String str = Common.SerializeHelper.SerializeLoopToString(userInfo);
                Session["userInfo"] = str;
                //使用Memcache代替Session解决数据在不同Web服务器之间共享
                Common.MemcacheHelper.Set(
                    sessionId,
                    str,
                    DateTime.Now.AddMinutes(20));
                Session["userinfo"] = userInfo;

                Model.UserInfo uAaaa = Session["userinfo"] as Model.UserInfo;



                //将Memcache的key以cookie的形式返回到浏览器的内存中,当用户再次请求其他页面的请求报文中会以Cookie将
                //该值在此发送到服务端
                Response.Cookies["sessionId"].Value = sessionId;  



                //  记住我 代码
                if (!string.IsNullOrEmpty(Request["checkMe"]))
                {
                    HttpCookie cookie1 = new HttpCookie("cp1", userInfo.UName);
                    HttpCookie cookie2 = new HttpCookie("cp2",
                      Common.WebCommon.GetMd5String(Common.WebCommon.GetMd5String(userInfo.UPwd))
                        );
                    cookie1.Expires = DateTime.Now.AddDays(3);
                    cookie2.Expires = DateTime.Now.AddDays(3);

                    Response.Cookies.Add(cookie1);
                    Response.Cookies.Add(cookie2);
                }


                return Content("ok:登录成功!" + totalTime);

            }
            else
            {
                return Content("no:登录失败!");
            }


            //  return Content("ok:登录成功!");
        }
        #endregion


        #region 判断Cookie信息
        private void CheckCookieInfo()
        {
            if (Request.Cookies["cp1"] != null && Request.Cookies["cp2"] != null)
            {
                string userName = Request.Cookies["cp1"].Value.ToString();
                string userPwd = Request.Cookies["cp2"].Value.ToString();
                var userInfo = UserInfoService.LoadEntities(u => u.UName == userName).FirstOrDefault();
                if (userInfo != null)
                {
                    //将用户的密码保存到数据库时一定要加密保存
                    string tmp = Common.WebCommon.GetMd5String(Common.WebCommon.GetMd5String(userInfo.UPwd));
                    if (tmp == userPwd)
                    {
                        String str = Common.SerializeHelper.SerializeLoopToString(userInfo);

                        string sessionId = Guid.NewGuid().ToString();
                        //使用Memcache代替Session解决数据在不同Web服务器之间共享
                        Common.MemcacheHelper.Set(
                            sessionId,
                            str,
                            DateTime.Now.AddMinutes(20));
                        //将Memcache的key以cookie的形式返回到浏览器的内存中,当用户再次请求其他页面的请求报文中会以Cookie将
                        //该值在此发送到服务端
                        Response.Cookies["sessionId"].Value = sessionId;
                        Response.Redirect("/Home/HomePage");

                    }
                }
                Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1);
                Response.Cookies["cp2"].Expires = DateTime.Now.AddDays(-1);


            }
        }
        #endregion



    
    }
}